const fs = require('fs');
const http = require('http');
const https = require('https');
const WebSocket = require('ws');
const webClient = require('./WebClient');

// =============== 配置区 ===============
const USE_WSS = true;    // true=wss，false=ws
const PORT = 8800;
const CERT_FILE = './cert.pem';
const KEY_FILE = './key.pem';

// =============== 创建HTTP/HTTPS服务器 ===============
let wsServer;
if (USE_WSS) {
    console.log('【HTTPS/WSS模式启动】');
    if (!fs.existsSync(CERT_FILE) || !fs.existsSync(KEY_FILE)) {
        console.error(`证书文件不存在！
请先生成：openssl req -newkey rsa:2048 -nodes -keyout key.pem -x509 -days 3650 -out cert.pem -subj "/CN=localhost"
`);
        process.exit(1);
    }
    const httpsOptions = {
        cert: fs.readFileSync(CERT_FILE),
        key: fs.readFileSync(KEY_FILE)
    };
    wsServer = https.createServer(httpsOptions, (req, res) => {
        res.writeHead(200);
        res.end('WSS服务已启动\n');
    });
} else {
    console.log('【HTTP/WS模式启动】');
    wsServer = http.createServer((req, res) => {
        res.writeHead(200);
        res.end('WS服务已启动\n');
    });
}

// =============== WebSocket服务启动 ===============
const wss = new WebSocket.Server({server: wsServer});

wss.on('connection', function connection(ws, req) {
    const ip = req.socket.remoteAddress;
    console.log('新客户端已连接', ip);

    ws.send(JSON.stringify({type: "notice", code: 0, msg: `欢迎，你的ip:${ip}`}));

    ws.on('message', async function incoming(message) {
        // ---- 安全解析 ----
        let obj;
        try {
            obj = JSON.parse(message.toString());
        } catch (e) {
            ws.send(JSON.stringify({type: "error", code: 1, msg: "请求内容需为合法JSON"}));
            return;
        }

        // 心跳直接返回可选
        if (obj.type === 'ping') {
            ws.send(JSON.stringify({type: "pong", code: 0, msg: "ok"}));
            return;
        }

        // 登录流程
        if (obj.type === 'login') {
            // 参数校验
            if (!obj.account || !obj.password) {
                ws.send(JSON.stringify({type: "login", code: 400, msg: "参数缺失", detail: {account: obj.account, password: !!obj.password}}));
                return;
            }

            let browser = null, page = null;
            try {
                // 启动自动化浏览器并登录
                ({browser, page} = await webClient.initPage());
                const data = await webClient.loginAndGetCaptcha(page, obj.account, obj.password);
                await webClient.delay(500);
                await webClient.clearAllCookies(page);

                // 无论成功与否都关闭浏览器并给前端答复
                if (browser) await browser.close();

                ws.send(JSON.stringify({
                    type: "login",
                    code: data.code,
                    msg: data.msg,
                    data: data.response
                }));
            } catch (e) {
                if (browser) try { await browser.close(); } catch {}
                ws.send(JSON.stringify({
                    type: "login",
                    code: 500,
                    msg: "服务内部异常: " + (e.message || e.toString())
                }));
            }
        } else {
            // 其它type
            ws.send(JSON.stringify({type: obj.type || "unknown", code: 404, msg: "暂不支持此操作"}));
        }
    });

    ws.on('close', () => {
        console.log('有客户端断开连接', ip);
    });
    ws.on('error', (err) => {
        console.error('客户端socket异常', err);
    });
});

// 启动 HTTP/HTTPS服务
wsServer.listen(PORT, () => {
    if (USE_WSS) {
        console.log(`WSS服务已启动：https://localhost:${PORT}/`);
        console.log(`WebSocket地址:  wss://localhost:${PORT}/`);
    } else {
        console.log(`WS服务已启动:  http://localhost:${PORT}/`);
        console.log(`WebSocket地址:  ws://localhost:${PORT}/`);
    }
});
